﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PipeAuto.DAL.PipeAutoDataSetTableAdapters;
using PipeAuto.DAL;
using Arthasliu.Uti;
using System.Threading;
using WinformAuthentication;

namespace PipeAuto.MgrPlatform
{
    public partial class StockOutForm : Form
    {
        public StockOutForm()
        {
            InitializeComponent();

            soInfoFlowLayoutPanel.AutoSize = true;
            soToolStrip.Visible = true;
            StockOutDocID = string.Empty;
            soDataGridView.AutoGenerateColumns = false;

            barEleIntelligentSuggestion.SuggestionAcceptedEvent += new Arthasliu.Controls.IntelligentSuggestion.SuggestionAcceptedEventHandler(barEleIntelligentSuggestion_SuggestionAcceptedEvent);


            try
            {
                BarcodeElementDicTableAdapter myAdapter = new BarcodeElementDicTableAdapter();

                for (int i = 0; i < 4;i++ )
                {
                    BarcodeElements[i] = myAdapter.GetDataByTypeState(i + 1, 1);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// operation state
        /// </summary>
        public MgrPlatformGlobal.OperationState OpState
        {
            get;
            set;
        }

        /// <summary>
        /// 
        /// </summary>
        public string StockOutDocID
        {
            get;
            set;
        }


        void barEleIntelligentSuggestion_SuggestionAcceptedEvent(object sender, TemplatedEventArgs<DataGridViewSelectedRowCollection> e)
        {
            var mySelectedRow = e.Data[0];

            //display text cell
            var myTextCell = soDataGridView.SelectedCells;


            if (myTextCell == null || myTextCell.Count == 0)
            {
                return;
            }

            //focus column name
            var myFocusName = soDataGridView.Columns[myTextCell[0].ColumnIndex].Name;

           


            //change display
            myTextCell[0].Value =gridViewEditControl.Text= mySelectedRow.Cells["title"].Value.ToString();

            //row index
            var myIndex = myTextCell[0].RowIndex;

            var myTable = soDataGridView.DataSource as PipeAutoDataSet.VisualStockOutRecsDataTable;


            //value data cell
            myTable[myIndex][myTextCell[0].OwningColumn.Name + "code"] = mySelectedRow.Cells["code"].Value;


        }

        private object autoCompleteLock = new object();

        private TextBox gridViewEditControl = null;

        private PipeAutoDataSet.BarcodeElementDicDataTable[] BarcodeElements = new PipeAutoDataSet.BarcodeElementDicDataTable[4];

        private void soAddToolStripButton_Click(object sender, EventArgs e)
        {

            //last index
            int myIndex = soDataGridView.Rows.Count - 1;

            //not the first row
            if (myIndex>=0)
            {

                soDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);

                //submit changes to data table
                soIDTitledTextBox.ContextTextBox.Focus();

                //avoid null value
                try
                {
                    soRowNotNull(myIndex);
                    checkQuantity(myIndex);
                }
                catch (MsgBoxException ex)
                {
                    MessageBox.Show(ex.Message,ex.Caption);
                    return;
                }
            }
                //first row
            else
            {

                soDataGridView.DataSource=new PipeAutoDataSet.VisualStockOutRecsDataTable(); 
            }


            var myTable=soDataGridView.DataSource as PipeAutoDataSet.VisualStockOutRecsDataTable;

            var myNewRow = myTable.NewVisualStockOutRecsRow();

            myNewRow.Sequence = soDataGridView.Rows.Count+1;
            myNewRow.ID = Guid.NewGuid().ToString();
            myNewRow.CateCode = myNewRow.TradeCode = myNewRow.PnCode = myNewRow.ColorCode = string.Empty;
            myNewRow.State = 1;
            myNewRow.Quantity = 0;

            //has not generate stock out document id
            if (OpState == MgrPlatformGlobal.OperationState.Add)
            {
                myNewRow.SetDocIDNull();
            }
            else
            {
                myNewRow.DocID = StockOutDocID;
            }

            myTable.AddVisualStockOutRecsRow(myNewRow);


        }

        /// <summary>
        /// make sure row not null
        /// </summary>
        /// <param name="cellIndex">cell's index</param>
        private void soRowNotNull(int cellIndex)
        {
            soElementNotNull(cellIndex, "cate","catecode");
            soElementNotNull(cellIndex, "trade","tradecode");
            soElementNotNull(cellIndex, "pn","pncode");
            soElementNotNull(cellIndex, "color","colorcode");
            soElementNotNull(cellIndex, "soquantitycolumn");
        }

        /// <summary>
        /// ensure quanity is validated
        /// </summary>
        /// <param name="rowIndex"></param>
        private void checkQuantity(int rowIndex)
        {
            var myTable = soDataGridView.DataSource as PipeAutoDataSet.VisualStockOutRecsDataTable;


            try
            {
                var myQuantity = int.Parse(myTable[rowIndex]["quantity"].ToString());

                if (myQuantity<=0)
                {
                    throw new MsgBoxException("第" + (rowIndex + 1) + "行的“数量”必须大于0，请检查", "错误");
                }
            }
            catch (FormatException)
            {
                throw new MsgBoxException("第" + (rowIndex + 1) + "行的“数量”不合法，请检查！", "错误");
            }
            catch (OverflowException)
            {
                throw new MsgBoxException("第" + (rowIndex + 1) + "行的“数量”太大，请检查！", "错误");
            }
        }

        /// <summary>
        /// ensure cell not null
        /// </summary>
        /// <param name="rowIndex"></param>
        /// <param name="textGridColumn">text grid view column name</param>
        /// <param name="valueDataColumn">value data column name</param>
        private void soElementNotNull(int rowIndex, string textGridColumn,string valueDataColumn="")
        {

            string myMsg = "第" + (rowIndex + 1) + "行的“" + soDataGridView.Columns[textGridColumn].HeaderText + "”不合法，请重新选择！";

            var myTable = soDataGridView.DataSource as PipeAutoDataSet.VisualStockOutRecsDataTable;

            //text data cell
            var myTextCell = myTable[rowIndex][soDataGridView.Columns[textGridColumn].DataPropertyName];

            //null value
            if (myTextCell==null||myTextCell.ToString()==string.Empty)
            {
                throw new MsgBoxException(myMsg, "错误");
            }

            //need check value cell
            if (valueDataColumn!="")
            {
                //value cell
                var myValueCell = myTable[rowIndex][valueDataColumn];

                if (myValueCell==null||myValueCell.ToString()==string.Empty)
                {
                    throw new MsgBoxException(myMsg, "错误");
                }
            }
        }

        private void soDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void soDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            var myTextBox = e.Control as TextBox;

            

            if (myTextBox == null)
            {
                return;
            }

            //clear tag
            myTextBox.Tag = string.Empty;

            //binding once
            if (barEleIntelligentSuggestion.Subscribed==false)
            {

                gridViewEditControl = myTextBox;

                //subscribe
                barEleIntelligentSuggestion.Subscribe(myTextBox);

                //initialize
                //hide column
                barEleIntelligentSuggestion.DisplayedColumns.Add("title");
                barEleIntelligentSuggestion.DisplayedColumns.Add("code");
                barEleIntelligentSuggestion.DisplayedColumns.Add("comment");

                //alia name
                barEleIntelligentSuggestion.ColumnAlias.Add("title", "名称");
                barEleIntelligentSuggestion.ColumnAlias.Add("code", "编码");
                barEleIntelligentSuggestion.ColumnAlias.Add("comment", "备注");

                //filter column
                barEleIntelligentSuggestion.FilterColumn = "pinyincode";

                //myTextBox.Leave += new EventHandler(myTextBox_Leave);
                myTextBox.GotFocus += new EventHandler(myTextBox_GotFocus);
                //myTextBox.TextChanged += new EventHandler(myTextBox_TextChanged);
            }

            if (soDataGridView.SelectedCells.Count==0)
            {
                return;
            }

            //clear old data source
            var myIntelDs = barEleIntelligentSuggestion.DataSource as DataTable;
            if (myIntelDs != null)
            {
                myIntelDs.Clear();
            }

            var myCell = soDataGridView.SelectedCells[0];

            barEleIntelligentSuggestion.ForceHide = false;

            PipeAutoDataSet.BarcodeElementDicDataTable myEleTable = null;

            //switch element type
            switch (myCell.ColumnIndex)
            {
                //category
                case 1:
                    {
                        myEleTable = BarcodeElements[0];
                        break;
                    }
                    //trademark
                case 2:
                    {
                        myEleTable = BarcodeElements[1];
                        break;
                    }
                    //partial number
                case 3:
                    {
                        myEleTable = BarcodeElements[2];
                        break;
                    }
                    //color
                case 4:
                    {
                        myEleTable = BarcodeElements[3];
                        break;
                    }
                default:
                    {
                        barEleIntelligentSuggestion.ForceHide = true;
                        break;
                    }
            }

            if (myEleTable!=null)
            {
                var myCloneEle = myEleTable.Clone();

                foreach (var myRow in myEleTable)
                {
                    myCloneEle.ImportRow(myRow);
                }

                barEleIntelligentSuggestion.DataSource = myCloneEle;
            }


        }

        void myTextBox_TextChanged(object sender, EventArgs e)
        {
            var myText=sender as TextBox;

            if (myText==null)
            {
                return;
            }

            var mySelectedCell = soDataGridView.SelectedCells;

            if (mySelectedCell.Count==0)
            {
                return;
            }

            var myTable = soDataGridView.DataSource as PipeAutoDataSet.VisualStockOutRecsDataTable;

            //text cell
            var myTextCell = myTable[mySelectedCell[0].RowIndex][mySelectedCell[0].ColumnIndex];

            //text has changed
            if (myTextCell!=null&&myTextCell.ToString()!=myText.Text)
            {
                //set text cell null
                //myTextCell = null;

                //updated
                soDataGridView.Rows[mySelectedCell[0].RowIndex].Cells["soopcolumn"].Value = MgrPlatformGlobal.OperationState.Update;

                //focus column name
                var myFocusName = soDataGridView.Columns[mySelectedCell[0].ColumnIndex].Name;

                //if value cell exist then set null
                try
                {
                    //myTable[mySelectedCell[0].RowIndex][myFocusName + "code"] = string.Empty;
                }
                catch (ArgumentException)
                {
                	
                }
                
            }

        }

        void myTextBox_GotFocus(object sender, EventArgs e)
        {
            var myText = sender as TextBox;
            if (myText==null)
            {
                return;
            }

            myText.SelectAll();
        }



        private void soCancelToolStripButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void StockOutForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否关闭窗口？","确认",MessageBoxButtons.YesNo)!=DialogResult.Yes)
            {
                e.Cancel=true;
            }
        }

        private void StockOutForm_Load(object sender, EventArgs e)
        {

            cusIntelligentSuggestion.Subscribe(soCustomTitledTextBox.ContextTextBox);

            cusIntelligentSuggestion.FilterColumn = "pinyincode";

            cusIntelligentSuggestion.DisplayedColumns.Add("title");
            cusIntelligentSuggestion.DisplayedColumns.Add("telephone");
            cusIntelligentSuggestion.DisplayedColumns.Add("contactor");
            cusIntelligentSuggestion.DisplayedColumns.Add("address");

            cusIntelligentSuggestion.ColumnAlias.Add("title", "名称");
            cusIntelligentSuggestion.ColumnAlias.Add("telephone", "联系电话");
            cusIntelligentSuggestion.ColumnAlias.Add("contactor", "收货人");
            cusIntelligentSuggestion.ColumnAlias.Add("address", "收货地址");

            cusIntelligentSuggestion.SuggestionAcceptedEvent += new Arthasliu.Controls.IntelligentSuggestion.SuggestionAcceptedEventHandler(cusIntelligentSuggestion_SuggestionAcceptedEvent);
            

            try
            {

                var myCusAdapter = new CustomInfoTableAdapter();
                var myCusTable = myCusAdapter.GetDataByState(1);
                cusIntelligentSuggestion.DataSource = myCusTable;

                //need load stock out information
                if (StockOutDocID!=string.Empty)
                {
                    //load doc
                    StockOutDocsTableAdapter mySoDocAdapter = new StockOutDocsTableAdapter();
                    var mySoDocTable = mySoDocAdapter.GetDataByID(StockOutDocID);

                    if (mySoDocTable.Count==0)
                    {
                        throw new Exception("找不到该出库单信息！");
                    }

                    soIDTitledTextBox.Context = mySoDocTable[0].ID;

                    //load custom information
                    var mySoCusTable = myCusAdapter.GetDataByID(mySoDocTable[0].CustomID);

                    soCustomTitledTextBox.Context = mySoCusTable[0].Title;
                    soCustomTitledTextBox.Tag = mySoCusTable[0].ID;


                    try
                    {
                        soContactTitledTextBox.Context = mySoCusTable[0].Contactor == null ? string.Empty : mySoCusTable[0].Contactor;
                    
                    }
                    catch (StrongTypingException)
                    {
                    	
                    }

                    try
                    {
                        soAddrTitledTextBox.Context = mySoCusTable[0].Address == null ? string.Empty : mySoCusTable[0].Address;
                    
                    }
                    catch (StrongTypingException)
                    {
                    	
                    }
                    
                    try
                    {

                        soTeleTitledTextBox.Context = mySoCusTable[0].Telephone == null ? string.Empty : mySoCusTable[0].Telephone;
                
                    }
                    catch (StrongTypingException)
                    {
                    	
                    }

                    //load records
                    VisualStockOutRecsTableAdapter mySoRecTable = new VisualStockOutRecsTableAdapter();

                    soDataGridView.DataSource = mySoRecTable.GetDataByDocID(StockOutDocID);

                    
                }
                else
                {
                    soDataGridView.DataSource = new PipeAutoDataSet.VisualStockOutDocsDataTable();
                }

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        void cusIntelligentSuggestion_SuggestionAcceptedEvent(object sender, TemplatedEventArgs<DataGridViewSelectedRowCollection> e)
        {
            var mySelectedRow = e.Data[0];

            soCustomTitledTextBox.Context = mySelectedRow.Cells["title"].Value.ToString();
            soCustomTitledTextBox.Tag = mySelectedRow.Cells["id"].Value.ToString();
            soTeleTitledTextBox.Context = mySelectedRow.Cells["telephone"].Value.ToString();
            soAddrTitledTextBox.Context = mySelectedRow.Cells["address"].Value.ToString();
            soContactTitledTextBox.Context = mySelectedRow.Cells["contactor"].Value.ToString();
        }

        private void soSaveToolStripButton_Click(object sender, EventArgs e)
        {
            //commit changes to data table
            soDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);

            //check custom information
            if (soCustomTitledTextBox.Tag==null||soCustomTitledTextBox.Tag.ToString() == string.Empty)
            {
                MessageBox.Show("客户名称不合法！");
                return;
            }

#if !DEBUG
            try
            {
#endif
                //empty stock out document
                if (soDataGridView.Rows.Count == 0)
                {

                    var myAllowEmptySoDoc = MgrPlatformGlobal.MgrConfiguration["allowemptystockoutdoc"];

                    if (myAllowEmptySoDoc != "true")
                    {
                        throw new Exception("出库单不能没有产品！");
                    }
                    else
                    {
                        if (MessageBox.Show("即将生成空出库单，是否继续？", "确认", MessageBoxButtons.YesNo) != DialogResult.Yes)
                        {
                            return;
                        }
                    }
                }

                //avoid invalidate value in grid view
                for (int i = 0; i < soDataGridView.Rows.Count; i++)
                {
                    var myOpCell = soDataGridView.Rows[i].Cells["soopcolumn"];

                    //not need to check
                    if (myOpCell.Value == null)
                    {
                        continue;
                    }

                    soRowNotNull(i);

                    //do not need to check any more
                    myOpCell.Value = null;
                }

                //get data source
                var mySoRecs = soDataGridView.DataSource as PipeAutoDataSet.VisualStockOutRecsDataTable;


                if (mySoRecs == null)
                {
                    return;
                }

                //whether should add new stock out doc
                switch (OpState)
                {
                    case MgrPlatformGlobal.OperationState.Add:
                        {
                            //new stock out doc id
                            var mySoDocId = MgrPlatformGlobal.GetSequence("stockoutdocs", "id");

                            //current user id
                            var myIdentity = Thread.CurrentPrincipal.Identity as WinformIdentity;

                            //new stock out
                            StockOutDocsTableAdapter mySoDocAdatper = new StockOutDocsTableAdapter();
                            mySoDocAdatper.NewStockOutDoc(mySoDocId, soCustomTitledTextBox.Tag.ToString(), myIdentity.ID);

                            //update sequence
                            var mySeqAdapter = new SequencesTableAdapter();
                            mySeqAdapter.UpdateSequence((decimal.Parse(mySoDocId) + 1).ToString(), "stockoutdocs", "id");

                            //display id
                            StockOutDocID = soIDTitledTextBox.Context = mySoDocId;

                            //set doc id
                            foreach (var mySoRecRow in mySoRecs)
                            {
                                mySoRecRow.DocID = StockOutDocID;
                            }

                            //no other operations
                            OpState = MgrPlatformGlobal.OperationState.Null;

                            break;
                        }
                }


                //apply changes
                soIDTitledTextBox.ContextTextBox.Focus();

                //update to db
                var mySoRecAdapter = new VisualStockOutRecsTableAdapter();
                var myChanges = mySoRecs.GetChanges() as PipeAutoDataSet.VisualStockOutRecsDataTable;


                if (myChanges != null)
                {

                    mySoRecAdapter.Update(myChanges);


                    //accept changes
                    mySoRecs.AcceptChanges();


                    MessageBox.Show("保存成功！");
                }
                else
                {
                    MessageBox.Show("没有需要保存的信息！");
                }


#if !DEBUG

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
#endif



        }

        private void soCustomTitledTextBox_ContextTextChanged(object sender, EventArgs e)
        {
            soCustomTitledTextBox.Tag = string.Empty;
        }

        private void soDelToolStripButton_Click(object sender, EventArgs e)
        {
            if (soDataGridView.SelectedCells.Count==0)
            {
                MessageBox.Show("请先选择一条记录！");
            }

            var myIndex = soDataGridView.SelectedCells[0].RowIndex;

            if (MessageBox.Show("即将删除第"+(myIndex+1)+"行数据，是否继续？","确认",MessageBoxButtons.YesNo)!=DialogResult.Yes)
            {
                return;
            }

            var myTable = soDataGridView.DataSource as PipeAutoDataSet.VisualStockOutRecsDataTable;


            //not the last row
            if (myIndex!=soDataGridView.Rows.Count-1)
            {
                for (int i = myIndex+1; i < soDataGridView.Rows.Count;i++ )
                {
                    myTable[i].Sequence = i ;
                }
            }


            myTable.Rows[myIndex].Delete();
        }


    }
}
